/**
 * 本地存储管理
 * 统一管理 LocalStorage 数据
 */

class StorageManager {
    constructor() {
        this.keys = {
            CUSTOM_WORDBOOKS: 'customWordbooks',
            RECITATION_DATA: 'recitationData',
            LEARNING_HISTORY: 'learningHistory',
            SESSIONS: 'sessions',
            WRONG_WORDS: 'wrongWords',
            STARRED_WORDS: 'starredWords',
            USER_SETTINGS: 'userSettings'
        };

        this.init();
    }

    init() {
        // 初始化默认数据结构
        this.initDefaultData();
    }

    /**
     * 初始化默认数据
     */
    initDefaultData() {
        // 如果是首次使用，初始化数据结构
        if (!this.get(this.keys.USER_SETTINGS)) {
            this.set(this.keys.USER_SETTINGS, {
                speechRate: 1.0,
                defaultMode: 'camelCase',
                fillInDifficulty: 2,
                autoPlayOnNext: false,
                showKeyboardShortcuts: true
            });
        }

        if (!this.get(this.keys.CUSTOM_WORDBOOKS)) {
            this.set(this.keys.CUSTOM_WORDBOOKS, []);
        }

        if (!this.get(this.keys.RECITATION_DATA)) {
            this.set(this.keys.RECITATION_DATA, {});
        }

        if (!this.get(this.keys.LEARNING_HISTORY)) {
            this.set(this.keys.LEARNING_HISTORY, {});
        }

        if (!this.get(this.keys.SESSIONS)) {
            this.set(this.keys.SESSIONS, []);
        }

        if (!this.get(this.keys.WRONG_WORDS)) {
            this.set(this.keys.WRONG_WORDS, {});
        }

        if (!this.get(this.keys.STARRED_WORDS)) {
            this.set(this.keys.STARRED_WORDS, []);
        }
    }

    /**
     * 获取数据
     */
    get(key) {
        try {
            const data = localStorage.getItem(key);
            return data ? JSON.parse(data) : null;
        } catch (error) {
            console.error(`读取数据失败: ${key}`, error);
            return null;
        }
    }

    /**
     * 保存数据
     */
    set(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
            return true;
        } catch (error) {
            console.error(`保存数据失败: ${key}`, error);
            
            // 检查是否是存储空间不足
            if (error.name === 'QuotaExceededError') {
                alert('存储空间不足！请清理一些历史数据。');
            }
            
            return false;
        }
    }

    /**
     * 删除数据
     */
    remove(key) {
        try {
            localStorage.removeItem(key);
            return true;
        } catch (error) {
            console.error(`删除数据失败: ${key}`, error);
            return false;
        }
    }

    /**
     * 清空所有数据
     */
    clear() {
        if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
            try {
                localStorage.clear();
                this.initDefaultData();
                alert('数据已清空');
                window.location.reload();
            } catch (error) {
                console.error('清空数据失败', error);
            }
        }
    }

    /**
     * 获取存储使用情况
     */
    getStorageUsage() {
        let total = 0;
        for (let key in localStorage) {
            if (localStorage.hasOwnProperty(key)) {
                total += localStorage[key].length + key.length;
            }
        }
        
        // 转换为 KB
        const usedKB = (total / 1024).toFixed(2);
        const limitKB = 5 * 1024; // 假设限制为 5MB
        const percentage = ((total / (limitKB * 1024)) * 100).toFixed(2);
        
        return {
            used: usedKB,
            limit: limitKB,
            percentage: percentage
        };
    }

    /**
     * 导出数据（用于备份）
     */
    exportData() {
        const data = {
            version: '1.0',
            exportDate: new Date().toISOString(),
            data: {
                customWordbooks: this.get(this.keys.CUSTOM_WORDBOOKS),
                recitationData: this.get(this.keys.RECITATION_DATA),
                learningHistory: this.get(this.keys.LEARNING_HISTORY),
                sessions: this.get(this.keys.SESSIONS),
                wrongWords: this.get(this.keys.WRONG_WORDS),
                starredWords: this.get(this.keys.STARRED_WORDS),
                userSettings: this.get(this.keys.USER_SETTINGS)
            }
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `englishreadcard-backup-${Date.now()}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    /**
     * 导入数据（从备份恢复）
     */
    importData(file) {
        const reader = new FileReader();
        
        reader.onload = (e) => {
            try {
                const data = JSON.parse(e.target.result);
                
                if (!data.version || !data.data) {
                    throw new Error('无效的备份文件格式');
                }

                // 确认导入
                if (confirm('导入数据将覆盖现有数据，是否继续？')) {
                    Object.keys(data.data).forEach(key => {
                        this.set(key, data.data[key]);
                    });
                    
                    alert('数据导入成功！');
                    window.location.reload();
                }
            } catch (error) {
                console.error('导入数据失败', error);
                alert('导入失败：' + error.message);
            }
        };

        reader.readAsText(file);
    }
}

// 全局实例
const storageManager = new StorageManager();
window.storageManager = storageManager;

